package org.darcy.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.darcy.entity.SysUser;
import org.darcy.framework.util.PasswordUtil;
import org.darcy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RememberAuthenticationInterceptor implements HandlerInterceptor {

	@Autowired
	private SysUserService userService;

	@Value("${app.shiro.loginUrl}")
	private String path;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			return true;
		}
		if (!subject.isRemembered()) {
			log.warn("未设置“记住我”,跳转到登录页...");
			response.sendRedirect(request.getContextPath() + path);
			return false;
		}
		try {
			Long userId = Long.parseLong(subject.getPrincipal().toString());
			SysUser user = userService.getById(userId);
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),
					PasswordUtil.decrypt(user.getPassword(), user.getUsername()), true);
			subject.login(token);
			log.info("[{}] - 已自动登录", user.getUsername());
		} catch (Exception e) {
			log.error("自动登录失败", e);
			response.sendRedirect(request.getContextPath() + path);
			return false;
		}
		return true;
	}
}
